package com.loadmore.oneday.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.loadmore.common.base.BaseActivity
import com.loadmore.common.base.BaseFragment
import com.loadmore.common.constants.Api
import com.loadmore.common.image.ImageLoader
import com.loadmore.common.image.PhotoUtil
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.model.User
import com.loadmore.common.net.Request.post
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.permission.PermissionCallback
import com.loadmore.common.router.Router
import com.loadmore.common.router.RouterPath
import com.loadmore.common.variables.Variables
import com.loadmore.oneday.R
import com.loadmore.oneday.adapter.MineSettingAdapter
import com.loadmore.oneday.model.MenuItem
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_LOADING
import kotlinx.android.synthetic.main.fragment_mine.*
import java.io.File
import java.util.*


class MineFragment:BaseFragment() {
    lateinit var adapter:MineSettingAdapter
    companion object {
        public fun newInstance(bundle: Bundle):MineFragment {
            val mineFragment = MineFragment()
            mineFragment.arguments = bundle
            return mineFragment
        }
    }
    override fun getLayoutId(): Int {
        return R.layout.fragment_mine
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        actionBarTitle("我的")
        setMenu(R.menu.mine_fragment)
        setRefreshEnable(true)
        setUserInfo()
        settingList.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        settingList.isNestedScrollingEnabled = false
        adapter = MineSettingAdapter(context)
        settingList.adapter = adapter
        adapter.appendItem(MenuItem(R.mipmap.icon_mine,"运动",RouterPath.Sport))
        adapter.appendItem(MenuItem(R.mipmap.icon_mine,"日程",RouterPath.Schedule))
        adapter.appendItem(MenuItem(R.mipmap.icon_mine,"个性皮肤",RouterPath.Skin))

        avatar.setOnClickListener {
            var activity:BaseActivity  = activity as BaseActivity
            activity.requestPermission(arrayOf(Manifest.permission.CAMERA),object :PermissionCallback {
                override fun onSettingBack() {

                }

                override fun onPermissionsDenied() {

                }

                override fun onPermissionsGranted() {
                    PhotoUtil.pickPhone(this@MineFragment)
                }

            })
        }


    }

    private fun setUserInfo() {
        name.text = Variables.user?.name
        introduction.text = Variables.user?.introduction
        ImageLoader.load(context!!,Variables.user?.avatar,avatar)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode === RESULT_OK) when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> {
                // 图片、视频、音频选择结果回调
                val selectList = PictureSelector.obtainMultipleResult(data)
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                uploadAvatar(selectList[0].compressPath)
            }
        }
    }

    override fun onMenuItemClick(menuItem: android.view.MenuItem) {
        super.onMenuItemClick(menuItem)
        Router.go(RouterPath.MineSetting,null)
    }

    private fun uploadAvatar(url:String) {
        var hashMap = HashMap<String,Any>()
        hashMap["avatar"] = File(url)
        hashMap["token"] = Variables.token!!
        val dialog:QMUITipDialog = QMUITipDialog.Builder(context).setIconType(ICON_TYPE_LOADING).setTipWord("正在上传...").create(false)
        dialog.show()
        post(Api.update, hashMap, object : JsonCallback<BaseResponse<User>>() {
            override fun onSuccess(response: Response<BaseResponse<User>>?) {
                dialog.dismiss()
                val result = response?.body()?.data
                Variables.user = result
                setUserInfo()
            }

            override fun uploadProgress(progress: Progress?) {
                super.uploadProgress(progress)



            }

            override fun onError(response: Response<BaseResponse<User>>?) {
                super.onError(response)
                dialog.dismiss()
            }

        })
    }

}